<template>
  <div>
    <!-- 展示具体小组信息的对话框 -->
    <KDialog v-model:showDialog="queryGroup.show">
      <template #header>
        <div style="font-size: 22px; font-family: 'Roboto Slab', serif">
          详细信息
        </div>
      </template>
      <el-scrollbar height="600px">
        <div style="font-family: 'Roboto Slab', serif;padding-top:20px;">
          <p><span class="QueryLabel">小组ID</span>{{ queryGroup.id }}</p>
          <p><span class="QueryLabel">小组密码</span>{{ queryGroup.password }}</p>
          <p><span class="QueryLabel">小组名称</span>{{ queryGroup.name }}</p>
          <p><span class="QueryLabel">描述信息</span>{{ queryGroup.desc }}</p>
          <p><span class="QueryLabel">创建时间</span>{{ queryGroup.CreatedAt }}</p>
          <p><span class="QueryLabel">创建者</span>{{ queryGroup.Owner }}</p>
          <div><span class="QueryLabel">小组成员</span>
          当前小组成员人数: {{ queryGroup.members.length }} 
          <hr>
          <div style="display:flex;">
            <div class="icon solid fa-seach"></div>
            <div style="width: 200px;display: flex;align-items: center;">
              <div style="display: inline;font-size: 18px;" class="icon solid fa-search">&ensp; 查询成员</div>
            </div>
            <input type="text" placeholder="输入学号或者姓名" class="MyInput" v-model="queryGroup.searchText">
          </div>
            <br>
              <div style="margin-left:10px;" v-html="queryGroup.results"></div>
          </div>  
        </div>
      </el-scrollbar>

    </KDialog>

    <!-- 删除小组的对话框 -->
    <KDialog v-model:showDialog="deleteGroup.show">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          删除小组 DEL
        </div>
      </template>
      <div align="center">
        <div style="font-size:18px;margin:30px 10px;">你确定要删除小组吗？</div>
        <div align="right">
          <button
            class="button primary"
            style="margin: 0 10px"
            @click="deleteGroup.handleConfirm"
          >
            确定
          </button>
          <button @click="deleteGroup.show = false" style="margin: 0 10px">
            取消
          </button>
        </div>
      </div>
    </KDialog>

    <!-- 提示去创建小组的对话框 -->
    <KDialog v-model:showDialog="gotoCreate.show">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          提示 INFO
        </div>
      </template>
      <div align="center">
        <div style="font-size:18px;margin:30px 10px;">你还未创建小组，是否现在去创建？</div>
        <div align="right">
          <button
            class="button primary"
            style="margin: 0 10px"
            @click="gotoCreate.handleConfirm"
          >
            确定
          </button>
          <button @click="gotoCreate.show = false" style="margin: 0 10px">
            取消
          </button>
        </div>
      </div>
    </KDialog>

    <!-- 修改信息的对话框 -->
    <KDialog v-model:showDialog="adjustGroup.show" width="50%">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          修改作业 ADJUST
        </div>
      </template>
      <div>
        <el-scrollbar height="600px">
          <adjust 
            v-if="adjustGroup.show" 
            :groupID="adjustGroup.groupID"
            @update="updateData"
          >
          </adjust>
        </el-scrollbar>
      </div>
    </KDialog>

    <section>
      <br />
      <KTitle3>我创建的小组 My Group</KTitle3>
      <br />
      <div v-if="createdGroup.group_num == 0" style="min-height: 1000px">
        <el-empty description="你貌似没有创建任何小组" :image-size="200" />
      </div>

      <div v-else style="min-height: 1100px">
        <div
          v-for="c in createdGroup.groups"
          :key="c.id"
        >
          <KCard style="margin: 40px; color: black">
            <template #header>
              <div style="display:flex;justify-content: space-between;}">
                <div
                  class="MyFont"
                  style="font-size: 22px; padding: 20px 10px 0px"
                >
                <span style="background-color:var(--mainColor);color:white;padding:8px;border-radius:.5em;">TEAM</span> &ensp; {{ c.name }}
                </div>
                <div>
                  <el-tooltip
                    content="查看小组详细信息"
                    placement="top"
                    effect="dark"
                  >
                    <button
                      style="
                        font-size: 12px;
                        margin: 20px 10px 0;
                        border-radius: 1.5em;
                      "
                      class="icon solid fa-comment-dots"
                      @click="queryGroup.query(c.id)"
                    >
                      细节
                    </button>
                  </el-tooltip>
                  <el-tooltip
                    content="修改作业的各项信息"
                    placement="top"
                    effect="dark"
                    >
                    <button
                      style="
                        font-size: 12px;
                        margin: 20px 10px 0;
                        border-radius: 1.5em;
                      "
                      class="icon primary solid fa-pen"
                      @click="adjustGroup.adjust(c.id)"
                    >
                      修改
                    </button>
                  </el-tooltip>
                  <el-tooltip
                    content="小心！这部操作会删除这个小组"
                    placement="top"
                    effect="dark"
                  >
                    <button
                      style="
                        font-size: 12px;
                        margin: 20px 10px 0;
                        border-radius: 1.5em;
                      "
                      class="icon solid fa-trash-alt"
                      @click="deleteGroup.delete(c.id)"
                    >
                      删除
                    </button>
                  </el-tooltip>
                </div>
              </div>
            </template>
            <div class="MyFont" style="font-size: 16px; padding: 10px">
              <p class="icon solid fa-object-group">
                &ensp;小组ID: {{ c.id }}
              </p>
              <p class="icon solid fa-closed-captioning">
                &ensp;小组描述:
                {{
                  c.desc
                    ? `「${c.desc}」`
                    : "无"
                }}
              </p>
              <p class="icon solid fa-hourglass-start">
                &ensp;创建时间:
                {{ makePrettyTime(c.CreatedAt) }}
              </p>
            </div>
          </KCard>
        </div>
      </div>
    </section>

    <section
      v-if="createdGroup.group_num > 0"
      align="center"
      style="font-family: 'Roboto Slab', serif"
    >
      <KPagination
        v-model:cur_page="createdGroup.cur_page"
        :total="createdGroup.total_pages"
        @click="createdGroup.move"
      ></KPagination>
    </section>
  </div>
</template>

<script>
import { onMounted, reactive, computed } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router"
import { ElNotification, ElLoading } from "element-plus";
import { makePrettyTime } from "@/hook/format"
import adjust from "@/pages/GroupCreate/adjust"

export default {
  name: "GroupCreate",
  components : {
    adjust
  },
  setup() {
    let store = useStore();
    let router = useRouter()

    function updateData() {
      const loading = ElLoading.service({
        lock: true,
        text: '正在拉起您的信息中...',
        background: 'rgba(0, 0, 0, 0.8)',
        customClass: "MyLoading"
      })
      store.dispatch("groupCreateNum").then(function () {
        if (store.state.group.groupCreateNum) {
          let queryIndice = createdGroup.cur_page_index
          let start = queryIndice[0];
          let end = queryIndice[queryIndice.length - 1] + 1
          // 最后一条需要在总条目之内
          end = Math.min(end, store.state.group.groupCreateNum)
          // 最后一条需要在100条请求条目之内
          end = Math.min(end, start + 100)

          store.dispatch("groupCreated", { start, end }).then(function () {
            loading.close()
            if (store.state.group.groupCreated.length > 0) {} 
            else {ElNotification({title: "Oops", message: "拉去初始化列表失败，错误信息: " + store.state.error})}
          });
        } 
        else {
          loading.close()
          let message
          if (store.state.group.groupCreateNum == 0) {
            gotoCreate.show = true;
            return
          }
          else {
            message = "不知道为啥，请求您创建的小组数量时出错了，错误信息: " + store.state.error
          }
          ElNotification({title: "Oops", message: message});
          return;
        }
      });
    }

    onMounted(updateData);

    let createdGroup = reactive({
      item_num : 10,
      groups: computed(() => store.state.group.groupCreated),
      group_num: computed(() => store.state.group.groupCreateNum),
      total_pages: computed(() => Math.ceil(createdGroup.group_num / createdGroup.item_num)),
      cur_page: 1,
      last_page : undefined,
      cur_page_index: computed(() => {
        let indexes = [], start = (createdGroup.cur_page - 1) * createdGroup.item_num;
        for ( let i = start; i < Math.min(start + createdGroup.item_num, createdGroup.group_num); ++ i) {
          indexes.push(i);
        }
        return indexes;
      }),
      move() {
        if (createdGroup.last_page != createdGroup.cur_page)
          updateData()
        createdGroup.last_page = createdGroup.cur_page
      }
    });

    let queryGroup = reactive({
      show: false,
      lastQueryGroupID : undefined,
      id : computed(() => store.state.group.groupQuery.id),
      password : computed(() => {
        let p = store.state.group.groupQuery.password
        // console.log(store.state.group.groupQuery)
        return (p.length > 0) ? p : "您无权限查看"
      }),
      name : computed(() => store.state.group.groupQuery.name),
      desc : computed(() => {
        if (store.state.group.groupQuery.desc)
          return store.state.group.groupQuery.desc
        else
          return "无"
      }),
      CreatedAt : computed(() => makePrettyTime(store.state.group.groupQuery.CreatedAt)),
      Owner : computed(() => {
        let owner = store.state.group.groupQuery.owner
        return `${owner.name} (ID ${owner.id})`
      }),  // 姓名与ID
      members : computed(() => {
        let mems = store.state.group.groupQuery.members || []
        let resmems = []
        for (let i = 0; i < mems.length; ++ i)
          resmems.push({name : mems[i].name, id : mems[i].id})
        return resmems;
      }),
      results : computed(() => {
        console.log(queryGroup.searchText)
        let resText = ""
        let count = 0;
        if (queryGroup.searchText.length == 0) {
          for (let i = 0; i < queryGroup.members.length; ++ i) {
            resText += "&emsp;&emsp;" + queryGroup.members[i].name;
            resText += "&emsp;&emsp;ID:" + queryGroup.members[i].id;
            if (i % 2 == 1) 
              resText += "<br>";
          }
        }
        else {
          if (/^[\d]*?$/g.test(queryGroup.searchText)) {    // 查询ID
            let searchID = parseInt(queryGroup.searchText)
            for (let i = 0; i < queryGroup.members.length; ++ i) {
              if (queryGroup.members[i].id == searchID) {
                count += 1;
                resText += "&emsp;&emsp;" + queryGroup.members[i].name;
                resText += "&emsp;&emsp;ID:" + queryGroup.members[i].id;
                if (count % 2 == 0) {
                  resText += "<br>"
                }
              }
            }
          }
          else {          // 查询人名
            for (let i = 0; i < queryGroup.members.length; ++ i) {
              if (queryGroup.members[i].name.includes(queryGroup.searchText)) {
                count += 1;
                resText += "&emsp;&emsp;" + queryGroup.members[i].name;
                resText += "&emsp;&emsp;ID:" + queryGroup.members[i].id;
                if (count % 2 == 0) {
                  resText += "<br>"
                }
              }
            }
          }
        }

        return resText
      }),
      searchText : "",
      query(groupID) {
        groupID = parseInt(groupID)        
        if (queryGroup.lastQueryGroupID == groupID) {    // 上一次请求是这个就不发送了
          queryGroup.show = true;
        }
        else {
          store.dispatch("queryGroup", {groupID}).then(function() {
            if (store.state.opSuccess === true) {
              store.state.opSuccess = undefined;
              queryGroup.show = true;
            }
            else {
              ElNotification({title : "Oops", message: "好像出了一点问题导致查询失败"})
            }
          })
        }
        queryGroup.lastQueryGroupID = groupID
      },
    });

    let deleteGroup = reactive({
      show: false,
      groupID : undefined,
      delete(groupID) {
        deleteGroup.show = true;
        deleteGroup.groupID = parseInt(groupID)
      },
      handleConfirm() {
        const loading = ElLoading.service({
          lock: true,
          text: '正在删除中...',
          background: 'rgba(0, 0, 0, 0.8)',
          customClass: "MyLoading"
        })
        store.dispatch("delGroup", {groupID : deleteGroup.groupID}).then(function() {
          if (store.state.opSuccess === true) {
            store.state.opSuccess = undefined
            store.dispatch("groupCreateNum").then(function () {
              if (store.state.group.groupCreateNum) {
                let start = 0;
                let end = Math.min(store.state.group.groupCreateNum, 100);
                store.dispatch("groupCreated", { start, end }).then(()=>{loading.close()})
                deleteGroup.show = false
                ElNotification({title : "删除成功！", message: "句点永远值得庆祝吗？"})
                updateData()
            }})
          }
          else {
            ElNotification({title: "Oops", message:"删除失败，原因如下：" + store.state.error})
            loading.close()
          }
        })
      }
    });

    let adjustGroup = reactive({
      show : false,
      groupID : undefined,
      adjust(groupID) {
        adjustGroup.groupID = parseInt(groupID)
        adjustGroup.show = true
      }
    })

    let gotoCreate = reactive({
      show : false,
      handleConfirm() {
        router.push("/newgroup")
        gotoCreate.show = false
      },
      handleCancel() {
        gotoCreate.show = false
      }
    })

    return {
      createdGroup,
      makePrettyTime,
      queryGroup,
      deleteGroup,
      gotoCreate,
      adjustGroup,
      updateData
    };
  },
};
</script>

<style>

.MyLoading {
  font-size : 30px;
  font-family: "Roboto Slab", serif;
}

.QueryLabel {
  font-size: auto;
  padding: 8px;
  margin-right: 10px;
  background-color: var(--mainColor);
  color: white;
  border-radius: 1.2em;
  font-family: "Roboto Slab", serif;
}

</style>